package bloomFilter;
import java.util.BitSet;

// 构建哈希函数
class SimpleHash {
    //容量
    private int cap;
    //随机种子
    private int seed;
    public SimpleHash(int cap, int seed) {
        this.cap = cap;
        this.seed = seed;
    }
    public int hash(String value) {
        int result = 0;
        int len = value.length();
        for (int i = 0; i < len; i++) {
            result = seed * result + value.charAt(i);
        }
        return (cap - 1) & result;
    }
}

public class BloomFilter {
    private static final  int  DEFAULT_SIZE  = 1 << 24 ;//方便哈希函数的计算
    private static final  int [] seeds = new  int []{5,7,11,13,31,37,61};

    private BitSet bits;     // 位图用来存储元素
    private SimpleHash[] func;  // 哈希函数所对应类
    private int size = 0;

    //初始化bits和func
    public  BloomFilter() {
        bits= new BitSet(DEFAULT_SIZE);
        func = new  SimpleHash[seeds.length];
        //把所有哈希对象进行初始化
        for( int  i= 0 ; i< seeds.length; i ++ ) {
            func[i]=new  SimpleHash(DEFAULT_SIZE, seeds[i]);
        }
    }

    public void  set(String value) {
        if(null == value)
            return;
        for(SimpleHash f : func) {
            bits.set(f.hash(value));
        }
        size++;
    }

    //判断这个数据（一定不存在，可能存在）
    public boolean contains(String value) {
        if (value == null) {
            return false;
        }
        for (SimpleHash f : func) {
            if (!bits.get(f.hash(value))) {
                return false;
            }
        }
        return true;//会有误判
    }

}
